We will now cover different ways of applying Image to the Background. Note that Background is added to a Frame View.
This is new View that is created when .frame modifier is applied to Text View which becomes child of new Frame View.
We start just with Text and .border to be able to see the actual size of the Text View.
Then we add .padding (before the .border) to increase the size of the Text View to better see what will happen to Image.
So the space between the String and the border is padding. Red border shows new size of the Text View.
Then we add a .frame which becomes new Parent of the Text View instead of the Root View.
We do this to be able to see parts of the Image that will go beyond the Parent.
When Image stretches beyond the Root View we can't see those parts.
We now add a .background Image of size 960 × 640. This is even bigger then the root View which is 800 x 400.
Image is positioned at the center of the Frame View and displayed in full size going beyond Root View in both directions.
If we add .resizable it will completely fill its Parent (Frame View) stretching in vertical direction.
To prevent stretching we add .aspectRatio(contentMode: .fit) which resizes Image until it hits one of Parent's borders.
Since our image is longer in width it will stop stretching when it hits horizontal borders of the Parent Frame View.
We now have empty spaces above and below the Image.
If we want our Image to completely cover Parent Frame View we can use .aspectRatio(contentMode: .fill).
This way it will continue increasing until both sets of Parent borders are hit (horizontal and vertical).
Now the Image has gone outside the Parent's borders in the horizontal direction.
To remove these parts we can apply .clipped modifier to Frame View.
We have to apply it AFTER the .background modifier or there will be nothing to clip.
.background modifier is applied to Frame but it returns back the Frame itself.
This is why if we now apply .clipped modifier it will be applied to the Frame View.
Example
struct ContentView: View {
var body: some View {
Text("Some text")
.padding(50)
.border(Color.red, width: 2)
.frame(width: 300, height:300).border(Color.blue, width: 2)
.background(Image("Table").resizable().aspectRatio(contentMode: .fill))
.clipped()
}
}